package com.ganzalang.gmall.fileread.controller;

import org.springframework.util.StringUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * @author Ganzalang
 * @descriptionj 读取指定路径的文件名
 * @Date 2021/10/5 12:39
 */
public class Main {

    public static void main(String[] args) throws IOException {
        // 待读取的文件名路径或文件夹路径
        String readFilePath = "D:\\N_m3u8DL-CLI_v2.9.1_with_ffmpeg_and_SimpleG\\Downloads";
        // 待写入文件的路径
        String writeFilePath = "D:\\N_m3u8DL-CLI_v2.9.1_with_ffmpeg_and_SimpleG";
        // 待写入文件的文件名
        String writeFileName = "non-C.txt";
        String content = readFileName(readFilePath);
        writeFile(writeFilePath, writeFileName, content);
    }

    /**
     * 将内容写入文件
     *
     * @param writeFilePath 写文件路径
     * @param writeFileName 文件名
     * @param content 文件内容
     */
    private static void writeFile(String writeFilePath, String writeFileName, String content) throws IOException {
        File file = new File(writeFilePath, writeFileName);
        // 文件存在则先删除
        if (file.exists()) {
            file.delete();
        }

        System.out.println("开始写入文件.");
        // 创建文件
        file.createNewFile();
        FileOutputStream outputStream = new FileOutputStream(file);
        byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
        outputStream.write(bytes);
        outputStream.close();
        System.out.println("已完成写入文件.");
    }


    /**
     * 读取文件名字
     *
     * @param filePath 读取路径
     * @return 读取到的内容
     */
    private static String readFileName(String filePath) {
        File file = new File(filePath);
        File[] files = file.listFiles();
        StringBuilder content = new StringBuilder();
        int count = 0;
        System.out.println("开始读取文件.");
        for (File subFile : files) {
            if (subFile.isDirectory()) {
                String fileName = Optional.ofNullable(subFile.getName()).filter(name -> !name.contains("-C")).orElse("");
                if (!StringUtils.isEmpty(fileName)) {
                    ++count;
                    content.append(fileName + "\n");
                }
            }
        }
        content.append("\ntotal count: " + count + "\n");
        System.out.println("完成读取文件.");
        return content.toString();
    }
}
